import React, { useState } from 'react';
import { createPost } from '../api';
import { useParams, useNavigate } from 'react-router-dom';

interface Props {
  onPosted?: () => void;
  onStartPost?: () => void;
}

const PostEditor: React.FC<Props> = ({ onPosted, onStartPost }) => {
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const { topicId } = useParams();
  const navigate = useNavigate();

  const handleSubmit = async () => {
    if (topicId && title.trim() && content.trim()) {
      await createPost({ title, content, topicId });
      setTitle('');
      setContent('');
      onPosted?.();
      navigate(`/topics/${topicId}`);
    }
  };

  return (
    <div>
      <input
        value={title}
        onChange={e => setTitle(e.target.value)}
        placeholder="动态标题"
        onFocus={onStartPost}
      />
      <textarea
        value={content}
        onChange={e => setContent(e.target.value)}
        placeholder="写点什么吧..."
        onFocus={onStartPost}
      />
      <button onClick={handleSubmit}>发表</button>
    </div>
  );
};

export default PostEditor;